package cn.tjie.user.service.impl;

import cn.tjie.basic.constant.WxConstants;
import cn.tjie.basic.dto.LoginDto;
import cn.tjie.basic.exception.BusinessException;
import cn.tjie.basic.jwt.JwtUtils;
import cn.tjie.basic.jwt.LoginData;
import cn.tjie.basic.jwt.RsaUtils;
import cn.tjie.basic.util.AjaxResult;
import cn.tjie.basic.util.HttpUtil;
import cn.tjie.basic.util.Md5Utils;
import cn.tjie.basic.util.StrUtils;
import cn.tjie.sys.domain.Menu;
import cn.tjie.user.domain.Logininfo;
import cn.tjie.user.domain.User;
import cn.tjie.user.domain.Wxuser;
import cn.tjie.user.mapper.LogininfoMapper;
import cn.tjie.user.mapper.UserMapper;
import cn.tjie.user.mapper.WxuserMapper;
import cn.tjie.user.service.ILogininfoService;
import cn.tjie.basic.service.impl.BaseServiceImpl;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    public Map<String, Object> account(LoginDto loginDto) {
        System.out.println(loginDto);
        //1.检验空值
        if(StringUtils.isEmpty(loginDto.getAccount())||StringUtils.isEmpty(loginDto.getCheckPass())){
            throw new BusinessException("登录信息不能为空！！！");
        }
        //2.校验账号和邮箱和电话
        Logininfo logininfo = logininfoMapper.findByAccount(loginDto);
        if(logininfo==null){
            throw new BusinessException("账号输入有误!!!");
        }
        //3.校验密码
        String byMd5 = Md5Utils.encrypByMd5(loginDto.getCheckPass() + logininfo.getSalt());
        if(!logininfo.getPassword().equals(byMd5)){
            throw new BusinessException("密码输入错误！！！");
        }
        //4.校验是否禁用
        if(!logininfo.getDisable()){
            throw new BusinessException("该账号已被禁用，请联系管理员解除");
        }
        //5，把登录信息保存在redis中，设置30分钟有效，key值随机生成用uuid
        Map<String, Object> map = loginSuccessJwtHandler(logininfo);
        return map;
    }

    @Override
    public AjaxResult wechatLogin(Map<String, String> map) {
        //发送第二个请求：需要什么code，appid，secret？返回什么？token，openid
        //1.准备第二个请求的地址
        String url = WxConstants.GET_ACK_URL.replace("APPID", WxConstants.APPID)
                .replace("SECRET", WxConstants.SECRET)
                .replace("CODE", map.get("code"));
        //2.使用HttpUtil发送微信登录请求：第二个请求，返回JSon格式字符串
        String jsonStr = HttpUtil.httpGet(url);
        //3.通过fastjson将json格式字符串转成json对象，方便获取access_token和openid
        JSONObject jsonObj = JSONObject.parseObject(jsonStr);
        //获取access_token和openid
        String access_token = jsonObj.getString("access_token");
        String openid = jsonObj.getString("openid");
        //4,通过openid查t_wxuser表，
        Wxuser wxuser=wxuserMapper.loadByOpenid(openid);
        if (wxuser!=null){//说明授权过，有记录
            User user = userMapper.loadById(wxuser.getUserId());
            if(user!=null){//说明授权过，在user里面有记录
                //免密登录
                Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
                //5，把登录信息保存在redis中，设置30分钟有效，key值随机生成用uuid
                Map<String, Object> resultMap = loginSuccessJwtHandler(logininfo);
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.setObj(resultMap);
                return ajaxResult;
            }

        }
        //4.2没有查询到，第一次扫码登录，把access_token和openid返回到前端，到绑定页面进行绑定
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setSuccess(false);
        ajaxResult.setMsg("没绑定");
        //https://api.weixin.qq.com/sns/auth?access_token=ACCESS_TOKEN&openid=OPENID
        ajaxResult.setObj("?access_token="+access_token+"&openid="+openid);
        return ajaxResult;
    }

    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String access_token = map.get("accessToken");
        String openid = map.get("openId");
        //1.校验电话和验证码是否为空
        if(StringUtils.isEmpty(phone)||StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("信息不能为空");
        }

        //2.校验手机验证码是否一致,是否过期key【业务键:手机号--验证码：时间戳】
        Object obj = redisTemplate.opsForValue().get("binder:" + phone);
        if(obj==null){
            //代表验证码过期
            throw new BusinessException("验证码已经过期");
        }

        //验证码是否一致
        String redisCode = obj.toString().split(":")[0];
        if(!redisCode.equals(verifyCode)){
            throw new BusinessException("验证码不一致");
        }
        //3.准备第三个请求--替换
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", access_token)
                .replace("OPENID", openid);
        //4.使用HttpUtil发送微信绑定请求，获得微信用户的信息--返回一个jsonStr
        String jsonStr = HttpUtil.httpGet(url);
        //5.使用fastjson处理JsonStr--将JSonObj里面的数据转给wxuser的数据
        JSONObject jsonObj = JSONObject.parseObject(jsonStr);
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(jsonObj.getString("openid"));
        wxuser.setNickname(jsonObj.getString("nickname"));
        wxuser.setHeadimgurl(jsonObj.getString("headimgurl"));
        wxuser.setUnionid(jsonObj.getString("unionid"));


        //6.创建User对象和logininfo对象【phone】
        //先判断之前是否使用手机号登陆过，但是没有绑定微信
        User user = userMapper.findByPhone(phone);
        if (user==null){
            User u = new User();
            u.setPhone(phone);
            u.setUsername(phone);
            u.setHeadImg(wxuser.getHeadimgurl());
            //盐值
            String salt = StrUtils.getComplexRandomString(32);
            u.setSalt(salt);
            //密码
            String pwd = StrUtils.getComplexRandomString(10);
            //加密
            String password = Md5Utils.encrypByMd5(pwd + salt);
            u.setPassword(password);

            //给logininfo设置值
            Logininfo logininfo = new Logininfo();
            //复制
            BeanUtils.copyProperties(u,logininfo);
            logininfoMapper.save(logininfo);
            u.setLogininfoId(logininfo.getId());
            userMapper.save(u);
            wxuser.setUserId(u.getId());
        }else{
            wxuser.setUserId(user.getId());
            wxuserMapper.save(wxuser);
        }
        //7.添加到数据库--先添加logininfo对象，获得自增长id（logininfo_id)，再添加user对象，获得自增长id(user_id)

        //8.做免密登录
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
        Map<String, Object> resultMap = loginSuccessJwtHandler(logininfo);
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setObj(resultMap);
        return ajaxResult;
    }

    private Map<String,Object> loginSuccessJwtHandler(Logininfo logininfo){
        Map<String,Object> map = new HashMap<>();//传给前端的
        LoginData loginData = new LoginData();//用来加密的

        //为了安全，先把登录信息的盐值和密码置空
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        loginData.setLogininfo(logininfo);
        map.put("logininfo",logininfo);

        if(logininfo.getType()==0){//type类型为0，是管理员
            //设置permissions
            List<String> permissions = logininfoMapper.findPermissionByLogininfoId(logininfo.getId());
            map.put("permissions",permissions);
            loginData.setPermissions(permissions);
            //设置menus
            List<Menu> menus = logininfoMapper.findMenuByLogininfoId(logininfo.getId());
            map.put("menus",menus);
            loginData.setMenus(menus);
        }
        //然后获取私钥进行加密
        try {
            //获取私钥
            PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            //利用私钥加密token
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30);
            map.put("token",jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
